<template>
  <div
    v-if="!initializing"
    class="vc-component editor-box"
    :style="editorStyle"
  >
    <Toolbar
      :editor="editorRef"
      :mode="mode"
      style="border-bottom: 1px solid #ccc"
    />
    <Editor
      v-model="pageData[currNode.name]"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ref, computed, shallowRef, inject, getCurrentInstance, nextTick, onMounted } from 'vue';
import visual from "@/visual/js/visual";
import EventHandler from "@/visual/js/event";

const props = defineProps({
  node: Object
});

const initializing = ref(true);
const pageData = inject("pageData", ref({}));
const currNode = ref(props.node);
const eventHandler = new EventHandler(
  inject('eventHandler', Function, true),
  getCurrentInstance(),
  currNode.value
);

const mode = ref('default');
const editorRef = shallowRef();

const init = async(styleId) => {
  initializing.value = true;
  visual.initStyle(currNode.value, styleId);
  mode.value = currNode.value.currCompStyle['mode'] || 'default';
  await nextTick(() => initializing.value = false);
};

const loadValue = async() => {
  const dataList = (await visual.loadData(currNode.value.compData, eventHandler, getData(), currNode.value)).data || [];
  pageData.value[currNode.value.name] = dataList.length > 0 && dataList[0]['内容'] || '';
};

const editorStyle = computed(() => {
  const compStyle = currNode.value.currCompStyle || {};
  let result = 'overflow-y: hidden;';
  result += visual.parseTplNs('width: {value};', compStyle['width'], 'px');
  result += visual.parseTplNs('height: {value};', compStyle['height'], 'px');
  result += visual.parseTpl('overflow: {value};', compStyle['overflow']);
  return result;
});

const handleCreated = (editor) => {
  editorRef.value = editor;
  editor.setHtml(pageData.value[currNode.value.name] || '');
};

const getData = () => {
  return {
    inputParam: currNode.value.inputParam,
    value: pageData.value[currNode.value.name]
  };
};

const changeStyle = (styleId) => {
  init(styleId);
};

const refresh = async() => {
  initializing.value = true;
  await loadValue();
  await nextTick(() => initializing.value = false);
};

onMounted(async() => {
  await init();
  await loadValue();
  await eventHandler.trigger('初始化事件');
});

defineExpose({ getData, changeStyle, refresh });
</script>

<style>
.w-e-toolbar {
  z-index: 503!important;
}
.w-e-menu {
  z-index: 502!important;
}
.w-e-text-container{
  z-index: 501!important;
}
</style>

<style scoped>
.editor-box {
  border: 1px solid #ccc;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}
</style>
